package com.taiji.dianthus.controller.sms;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taiji.dianthus.common.BasicController;
import com.taiji.dianthus.common.BusinessMessage;
import com.taiji.dianthus.domain.sms.SmsAccount;
import com.taiji.dianthus.domain.sys.DSysUser;
import com.taiji.dianthus.service.sms.SmsAccountService;
import com.taiji.dianthus.service.sys.SysLogService;
import com.taiji.dianthus.util.ExcelUtil;
import com.taiji.dianthus.util.IPUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

import static com.taiji.dianthus.common.Constant.*;

@RequestMapping(value = "/sms/account")
@Controller
public class SmsAccountController extends BasicController {
    @Autowired
    private SmsAccountService accountService;
    @Autowired
    private SysLogService sysLogService;

    /**
     * 查询短信账号列表
     *
     * @param request
     * @param model
     * @param pageSize
     * @param currentPage
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(HttpServletRequest request, Model model, Integer pageSize, Integer currentPage, String userAccount, String addSerial) {
        pageSize = getPageSize(pageSize);
        currentPage = getCurrentPage(currentPage);
        DSysUser currentUser = currentUser();
        BusinessMessage message = accountService.list(pageSize, currentPage, userAccount, addSerial);

        sysLogService.save(currentUser, LOG_OPERATION_QUERY, IPUtil.getIpAddr(request),
                "查询短信账号列表", message.getSuccess() ? 1 : 0, message.getMsg());
        StringBuffer url = new StringBuffer("/sms/account/list?pageSize=10");
        if (!StringUtils.isEmpty(userAccount)) {
            url.append("&userAccount=" + userAccount);
            model.addAttribute("userAccount", userAccount);
        }
        if (!StringUtils.isEmpty(addSerial)) {
            url.append("&addSerial=" + addSerial);
            model.addAttribute("addSerial", addSerial);
        }
        model.addAttribute("url", url);
        model.addAttribute("currentUser", currentUser);
        model.addAttribute("menus", listMenu());
        model.addAttribute("data", message.getData());
        return "pages/sms/accountInfoList";
    }

    /**
     * 跳转新增/编辑页面
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/add")
    public String addRole(Model model, String id) {
        SmsAccount smsAccount = new SmsAccount();
        if (!StringUtils.isEmpty(id)) {
            smsAccount = accountService.getById(id);
        }
        model.addAttribute("smsAccount", smsAccount);
        model.addAttribute("currentUser", currentUser());
        model.addAttribute("menus", listMenu());
        return "/pages/sms/accountInfoAdd";
    }

    @RequestMapping(value = "/save")
    @ResponseBody
    public BusinessMessage saveRole(HttpServletRequest request, Model model, SmsAccount smsAccount) {
        BusinessMessage message = accountService.saveAccount(smsAccount, currentUser());
        //保存操作日志
        if (!StringUtils.isEmpty(smsAccount.getId())) {
            sysLogService.save(currentUser(), LOG_OPERATION_SAVE, IPUtil.getIpAddr(request),
                    "保存短信账号信息", message.getSuccess() ? 1 : 0, message.getMsg());
        } else {
            sysLogService.save(currentUser(), LOG_OPERATION_UPDATE, IPUtil.getIpAddr(request),
                    "更新短信账号应用[" + smsAccount.getUserAccount() + "]信息", message.getSuccess() ? 1 : 0, message.getMsg());
        }
        message.setUrl("/sms/account/list");
        return message;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public BusinessMessage delete(HttpServletRequest request, String id) {
        BusinessMessage message = accountService.deleteById(id);
        sysLogService.save(currentUser(), LOG_OPERATION_DEL,
                IPUtil.getIpAddr(request), "删除短信账号记录", message.success ? 1 : 0, message.getMsg());
        return message;
    }

    @RequestMapping("/checkAddSerial")
    @ResponseBody
    public BusinessMessage checkAddSerial(HttpServletRequest request, String baseNumber, String extendNumber, String id) {
        BusinessMessage message = accountService.checkAddSerial(baseNumber, extendNumber, id);
        return message;
    }

    /**
     * 批量导入终端信息
     *
     * @param request
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    public JSONObject uploadingFile(HttpServletRequest request,@RequestParam(value = "file",required = false) MultipartFile file) {
        JSONObject oo = new JSONObject();
        oo.put("success", false);
        oo.put("msg", "上传失败");
        Boolean bool = ExcelUtil.checkFile(file);
        if (!bool) {
            oo.put("msg", "文件类型不正确或为空");
            oo.put("success", false);
            return oo;
        }
        JSONArray result = new JSONArray();
        try {
            Sheet sheet = ExcelUtil.getDataFromExcel(file);
            //获得数据的总行数
            int totalRowNum = sheet.getLastRowNum();
            //要获得属性
            for (int i = 1; i <= totalRowNum; i++) {
                String userAccount = "";
                String userPassword = "";
                String ecName = "";
                String sign = "";
                String baseNumber = "";
                String extendNumber = "";
                String addSerial = "";
                Integer isOutCall = 0;
                Integer sortNumber = 0;

                //获得第i行对象
                Row row = sheet.getRow(i);
                //空间位置(为空则停止解析)
                Cell cell = row.getCell(1);
                //账号
                if (cell != null && !"".equals(cell)) {
                    cell.setCellType(CellType.STRING);
                    userAccount = cell.getStringCellValue() + "";
                }
                //密码
                cell = row.getCell(2);
                if (cell != null && !"".equals(cell)) {
                    cell.setCellType(CellType.STRING);
                    userPassword = cell.getStringCellValue() + "";

                }
                //企业名称
                cell = row.getCell(3);
                if (cell != null && !"".equals(cell)) {
                    cell.setCellType(CellType.STRING);
                    ecName = cell.getStringCellValue() + "";
                }
                //签名编号
                cell = row.getCell(4);
                if (cell != null && !"".equals(cell)) {
                    cell.setCellType(CellType.STRING);
                    sign = cell.getStringCellValue() + "";
                }
                //基础账号
                cell = row.getCell(5);
                if (cell != null && !"".equals(cell)) {
                    cell.setCellType(CellType.STRING);
                    baseNumber = cell.getStringCellValue() + "";
                }
                //扩展账号
                cell = row.getCell(6);
                if (cell != null && !"".equals(cell)) {
                    cell.setCellType(CellType.STRING);
                    extendNumber = cell.getStringCellValue() + "";
                }
                //排序
                cell = row.getCell(7);
                if (cell != null && !"".equals(cell)) {
                    cell.setCellType(CellType.NUMERIC);
                    sortNumber = (int) cell.getNumericCellValue();
                }
                //是否外部调用账号(0为本系统调用  1为外部调用)
                cell = row.getCell(8);
                if (cell != null && !"".equals(cell)) {
                    cell.setCellType(CellType.NUMERIC);
                    isOutCall = (int) cell.getNumericCellValue();
                }

                SmsAccount account = new SmsAccount();
                account.setUserAccount(userAccount);
                account.setUserPassword(userPassword);
                account.setEcName(ecName);
                account.setSign(sign);
                account.setBaseNumber(baseNumber);
                account.setExtendNumber(extendNumber);
                account.setAddSerial(baseNumber + extendNumber);
                account.setIsOutCall(isOutCall);
                account.setSortNumber(sortNumber);
                account.setEnableFlag(1);
                /*查询基础代码加扩展号码是否已存在  不存在则插入*/
                BusinessMessage message = accountService.checkAddSerial(baseNumber, extendNumber, null);
                if (!message.getSuccess()) {
                    //说明不存在
                    accountService.saveAccount(account, currentUser());
                }
            }
            oo.put("success", true);
            oo.put("msg", "上传成功");
            sysLogService.save(currentUser(), LOG_OPERATION_SAVE,
                    IPUtil.getIpAddr(request), "批量导入账号信息", 1, "");
        } catch (Exception e) {
            e.printStackTrace();
            oo.put("success", false);
            oo.put("msg", "上传失败");
        }
        return oo;
    }
}
